const joi = require('joi');
const dbQuery = require('../model/db');
const {
	sendError,
	sendSuccess
} = require('../utils/sendFunction');

// 验证规则
const schemaAddgedanTag = joi.object({
	name: joi.string().required().error(new Error('name不符合验证规则')),
	create_time: joi.string().required().error(new Error('create_time不符合验证规则')),
})

const schemaEditgedanTag = joi.object({
	id: joi.number().required().error(new Error('id不符合验证规则')),
	name: joi.string().required().error(new Error('name不符合验证规则')),
})

const schemaDeleteAndGetgedanTag = joi.object({
	id: joi.number().required().error(new Error('id不符合验证规则'))
})

const schemaGetGedanByUserId = joi.object({
	id: joi.number().required().error(new Error('id不符合验证规则'))
})

const schemaGetGedanByGedanTagId = joi.object({
	id: joi.number().required().error(new Error('id不符合验证规则'))
})

const schemaGetGedanById = joi.object({
	id: joi.number().required().error(new Error('id不符合验证规则'))
})

// userid title pic musicid introduction gedantagid
const schemaAddgedan = joi.object({
	userid: joi.number().required().error(new Error('userid不符合验证规则')),
	title: joi.string().required().error(new Error('title不符合验证规则')),
	musicid: joi.string().required().error(new Error('musicid不符合验证规则')),
	introduction: joi.string().required().error(new Error('introduction不符合验证规则')),
	gedantagid: joi.number().required().error(new Error('gedantagid不符合验证规则'))
})

// 管理员可以修改 title pic introduction 但全部需返回
// id title pic musicid introduction gedantagid
const schemaEditgedan = joi.object({
	id: joi.number().required().error(new Error('id不符合验证规则')),
	title: joi.string().required().error(new Error('title不符合验证规则')),
	musicid: joi.string().required().error(new Error('musicid不符合验证规则')),
	introduction: joi.string().required().error(new Error('introduction不符合验证规则')),
	gedantagid: joi.number().required().error(new Error('gedantagid不符合验证规则'))
})

// id
const schemaDeletegedan = joi.object({
	id: joi.number().required().error(new Error('id不符合验证规则'))
})

// name create_time
const addTag = async function (req, res, next) {
	let {
		name,
		create_time
	} = req.body;

	if (!name || !create_time) {
		sendError(res, 200, '歌单类型名称或创建时间不能为空!');
		return;
	}

	try {
		await schemaAddgedanTag.validateAsync({
			name,
			create_time
		})
	} catch (error) {
		next(error);
		return;
	}

	let sqlStr = 'select * from gedantag where gedantag_name=?'
	let result = await dbQuery(sqlStr, name);
	if (result.length !== 0) {
		sendError(res, 200, '歌单类型名称被占用，请更换其他歌单类型名称!');
		return;
	}

	let sqlStr1 = 'insert into gedantag (gedantag_name,gedantag_create_time) values (?,?)';
	let result1 = await dbQuery(sqlStr1, [name, create_time]);
	if (result1.affectedRows == 1) {
		sendSuccess(res, '添加歌单类型成功!');
	} else {
		sendError(res, 500, '添加歌单类型失败，请稍后再试!')
	}

}

// id name(new)
const editTag = async function (req, res, next) {
	let {
		id,
		name
	} = req.body;

	if (!name || !id) {
		sendError(res, 200, '歌单类型名称或id不能为空!');
		return;
	}

	try {
		await schemaEditgedanTag.validateAsync({
			name,
			id
		})
	} catch (error) {
		next(error);
		return;
	}

	let sqlStr = 'select * from gedantag where gedantag_name=? and gedantagid!=?'
	let result = await dbQuery(sqlStr, [name, id]);
	if (result.length !== 0) {
		sendError(res, 200, '歌单类型名称已被占用，请更换后重试!');
		return;
	}

	let sqlStr1 = 'update gedantag set gedantag_name=? where gedantagid=?'
	let result1 = await dbQuery(sqlStr1, [name, id]);
	if (result1.affectedRows == 1) {
		sendSuccess(res, '修改歌单类型成功!');
	} else {
		sendError(res, 500, '修改歌单类型失败，请稍后再试!')
	}
}

// id
const deleteTag = async function (req, res, next) {
	let {
		id
	} = req.query;

	if (!id) {
		sendError(res, 200, 'id不能为空!');
		return;
	}

	try {
		await schemaDeleteAndGetgedanTag.validateAsync({
			id
		})
	} catch (error) {
		next(error);
		return;
	}

	let sqlStr = 'select * from gedan where gedantag_id=?';
	let result = await dbQuery(sqlStr, [id]);
	if (result.length !== 0) {
		sendError(res, 200, '删除歌单类型失败，该歌单类型中有歌单!')
		return;
	}

	let sqlStr1 = 'delete from gedantag where gedantagid=?'
	let result1 = await dbQuery(sqlStr1, [id]);
	if (result1.affectedRows == 1) {
		sendSuccess(res, '删除歌单类型成功!');
	} else {
		sendError(res, 500, '删除歌单类型失败，请稍后再试!')
	}
}

const getTag = async function (req, res, next) {
	let sqlStr = 'select * from gedantag';
	let result = await dbQuery(sqlStr);
	if (result.length >= 0) {
		sendSuccess(res, '获取歌单类型成功!', {
			data: result
		})
	} else {
		sendError(res, 500, '获取歌单类型失败，请稍后再试!')
	}
}

// id
const getTagById = async function (req, res, next) {
	let {
		id
	} = req.query;

	if (!id) {
		sendError(res, 200, 'id不能为空!');
		return;
	}

	try {
		await schemaDeleteAndGetgedanTag.validateAsync({
			id
		})
	} catch (error) {
		next(error);
		return;
	}

	let sqlStr = 'select * from gedantag where gedantagid=?';
	let result = await dbQuery(sqlStr, [id]);
	if (result.length >= 0) {
		sendSuccess(res, '获取歌单类型成功！', {
			data: result
		})
		return;
	} else {
		sendError(res, 500, '获取歌单类型失败，请稍后再试！')
	}
}

// userid title pic musicid introduction gedantagid
const addGedan = async function (req, res, next) {
	let info = req.body;

	if (!info.userid || !info.title || !info.introduction || !info.gedantagid || !info.musicid) {
		sendError(res, 200, 'userid或歌单名称或歌单描述或歌单类型或musicid不能为空！')
		return;
	}

	if (!req.file) {
		sendError(res, 200, '图片不能为空！')
		return;
	}

	try {
		await schemaAddgedan.validateAsync({
			userid: info.userid,
			title: info.title,
			musicid: info.musicid,
			introduction: info.introduction,
			gedantagid: info.gedantagid,
		})
	} catch (error) {
		next(error);
		return;
	}

	let sqlStr = 'select * from gedan where gedan_title=?';
	let result = await dbQuery(sqlStr, info.title);
	if (result.length !== 0) {
		sendError(res, 200, '歌单名称被占用，请更换其他歌单名称!');
		return;
	}

	let img = req.file.path.split('server\\')[1].replace('\\', '/').replace('\\', '/');

	let sqlStr1 = 'insert into gedan (gedan_user_id,gedan_title,gedan_pic_url,gedan_music_id,gedan_introduction,gedantag_id) values (?,?,?,?,?,?)';
	let result1 = await dbQuery(sqlStr1, [info.userid, info.title, img, info.musicid, info.introduction, info.gedantagid]);
	if (result1.affectedRows == 1) {
		sendSuccess(res, '添加歌单成功!');
	} else {
		sendError(res, 500, '添加歌单失败，请稍后再试!')
	}
}

// id
const deleteGedan = async function (req, res, next) {
	let {
		id
	} = req.query;

	if (!id) {
		sendError(res, 200, 'id不能为空！')
	}

	try {
		await schemaDeletegedan.validateAsync({
			id
		})
	} catch (error) {
		next(error);
		return;
	}

	let sqlStr = 'delete from gedan where gedanid=?'
	let result = await dbQuery(sqlStr, [id]);
	let sqlStr1 = 'delete from collect where gedan_id=?';
	let result1 = await dbQuery(sqlStr1, [id]);
	let sqlStr2 = 'delete from comment where gedan_id=?';
	let result2 = await dbQuery(sqlStr2, [id]);
	if (result.affectedRows == 1 && result1.affectedRows >= 0 && result2.affectedRows >= 0) {
		sendSuccess(res, '删除歌单成功!');
	} else {
		sendError(res, 500, '删除歌单失败,请稍后再试！');
	}
}

const getGedan = async function (req, res, next) {
	let sqlStr = 'select gedan.*,gedantag.*,user.userid,user.username,user.user_nickname from gedan inner join gedantag on gedan.gedantag_id=gedantag.gedantagid inner join user on gedan.gedan_user_id=user.userid';

	let result = await dbQuery(sqlStr);

	if (result.length >= 0) {
		sendSuccess(res, '获取歌单成功!', {
			data: result
		})
	} else {
		sendError(res, 500, '获取歌单失败，请稍后再试!')
	}
}

// userid
const getGedanByUserId = async function (req, res, next) {
	let {
		userid
	} = req.query;

	if (!userid) {
		sendError(res, 200, 'userid不能为空！');
	}

	try {
		await schemaGetGedanByUserId.validateAsync({
			id: userid
		})
	} catch (error) {
		next(error);
		return;
	}

	let sqlStr = 'select gedan.*,gedantag.*,user.userid,user.username,user.user_nickname from gedan inner join gedantag on gedan.gedantag_id=gedantag.gedantagid inner join user on gedan.gedan_user_id=user.userid where gedan.gedan_user_id=? order by gedan.gedanid desc'
	let result = await dbQuery(sqlStr, [userid]);
	if (result.length >= 0) {
		sendSuccess(res, '获取歌单成功!', {
			data: result
		})
	} else {
		sendError(res, 500, '获取歌单失败，请稍后再试!')
	}
}

// id title pic musicid introduction gedantagid
const editGedan = async function (req, res, next) {
	let info = req.body;

	if (!info.id || !info.title || !info.introduction || !info.gedantagid || !info.musicid) {
		sendError(res, 200, 'id或歌单名称或歌单描述或歌单类型或musicid不能为空！')
		return;
	}

	try {
		await schemaEditgedan.validateAsync({
			id: info.id,
			title: info.title,
			musicid: info.musicid,
			introduction: info.introduction,
			gedantagid: info.gedantagid,
		})
	} catch (error) {
		next(error);
		return;
	}

	let sqlStr = 'select * from gedan where gedan_title=? and gedanid!=?';
	let result = await dbQuery(sqlStr, [info.title, info.id]);
	if (result.length !== 0) {
		sendError(res, 200, '歌单名称被占用，请更换其他歌单名称!');
		return;
	}

	if (req.file) {
		let img = req.file.path.split('server\\')[1].replace('\\', '/').replace('\\', '/');
		let sqlStr1 = 'update gedan set gedan_title=?,gedan_pic_url=?,gedan_music_id=?,gedan_introduction=?,gedantag_id=? where gedanid=?';
		let result1 = await dbQuery(sqlStr1, [info.title, img, info.musicid, info.introduction, info.gedantagid, info.id]);
		if (result1.affectedRows == 1) {
			sendSuccess(res, '修改gedan成功!');
		} else {
			sendError(res, 500, '修改gedan失败，请稍后再试!')
		}
	} else {
		let sqlStr2 = 'update gedan set gedan_title=?,gedan_music_id=?,gedan_introduction=?,gedantag_id=? where gedanid=?';
		let result2 = await dbQuery(sqlStr2, [info.title, info.musicid, info.introduction, info.gedantagid, info.id]);
		if (result2.affectedRows == 1) {
			sendSuccess(res, '修改歌单成功!');
		} else {
			sendError(res, 500, '修改歌单失败，请稍后再试!')
		}
	}
}

// gedantagid
const getGedanByGedanTagId = async function (req, res, next) {
	let {
		gedantagid
	} = req.query;

	if (!gedantagid) {
		sendError(res, 200, '歌单类型不能为空！');
	}

	try {
		await schemaGetGedanByGedanTagId.validateAsync({
			id: gedantagid
		})
	} catch (error) {
		next(error);
		return;
	}

	let sqlStr = 'select gedan.*,gedantag.*,user.userid,user.username,user.user_nickname from gedan inner join gedantag on gedan.gedantag_id=gedantag.gedantagid inner join user on gedan.gedan_user_id=user.userid where gedan.gedantag_id=?'
	let result = await dbQuery(sqlStr, [gedantagid]);
	if (result.length >= 0) {
		sendSuccess(res, '获取歌单成功!', {
			data: result
		})
	} else {
		sendError(res, 500, '获取歌单失败，请稍后再试!')
	}
}

// id
const getGedanById = async function (req, res, next) {
	let {
		id
	} = req.query;

	if (!id) {
		sendError(res, 200, 'id不能为空！')
		return
	}

	try {
		await schemaGetGedanById.validateAsync({
			id
		})
	} catch (error) {
		next(error)
		return
	}

	let sqlStr = 'select gedan.*,gedantag.*,user.userid,user.username,user.user_nickname from gedan inner join gedantag on gedan.gedantag_id=gedantag.gedantagid inner join user on gedan.gedan_user_id=user.userid where gedan.gedanid=?'
	let result = await dbQuery(sqlStr, [id]);
	if (result.length >= 0) {
		sendSuccess(res, '获取歌单成功!', {
			data: result
		})
	} else {
		sendError(res, 500, '获取歌单失败，请稍后再试!')
	}
}

module.exports = {
	getGedanById,
	getGedanByGedanTagId,
	addTag,
	editTag,
	deleteTag,
	getTag,
	addGedan,
	deleteGedan,
	getGedan,
	editGedan,
	getTagById,
	getGedanByUserId
}